package com.jingnen.guess_index_server.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jingnen.guess_index_server.dto.RegisterDTO;
import com.jingnen.guess_index_server.entity.User;
import com.jingnen.guess_index_server.exception.UserNameExistsException;
import com.jingnen.guess_index_server.service.UserService;

import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody RegisterDTO dto) {
        try {
            User user = userService.register(dto.userName(), dto.password());
            return ResponseEntity.ok(user);
        } catch (UserNameExistsException e) {
            return ResponseEntity.badRequest().body(Map.of(
                "error", "USERNAME_EXISTS",
                "message", "用户名已存在"
            ));
        }
    }
}
